package com.wctj.api.business.common.aspect;

import com.wctj.api.base.annotation.SysLog;
import com.wctj.api.base.entity.DdwxSysLog;
import com.wctj.api.base.utils.HttpContextUtil;
import com.wctj.api.base.utils.IPUtil;
import com.wctj.api.base.utils.JacksonUtil;
import com.wctj.api.base.utils.TimeUtils;
import com.wctj.api.business.common.service.DdwxSysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/** 
* @Description: 支付系统日志，切面处理类
* @Author: lydms
* @Date: 2024/10/29
*/
@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private DdwxSysLogService ddwxSysLogService;

    @Pointcut("@annotation(com.wctj.api.base.annotation.SysLog)")
    public void logPointCut() {

    }

    @Before("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) throws NoSuchMethodException {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());


        DdwxSysLog sysLog = new DdwxSysLog();
        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            //注解上的描述
            sysLog.setOperation(syslog.value());
        }
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JacksonUtil.getNormalPatternJsonString(args[0]);
        sysLog.setParams(params);
        //请求相关信息
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtil.getLocalIp(request));
        sysLog.setMethod(request.getRequestURI());

        sysLog.setCreateDate(TimeUtils.getNow());
        //保存系统日志
        ddwxSysLogService.save(sysLog);
    }

}
